package com.qf.controller;


import com.qf.pojo.Address;

import com.qf.pojo.Area;
import com.qf.pojo.User;
import com.qf.service.AddressService;
import com.qf.service.AreaService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.AreaServiceImpl;
import com.qf.utils.SYS;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;


public class AddressController extends Base {
    private AreaService areaService=new AreaServiceImpl();
    private AddressService addressServic=new AddressServiceImpl();

    //新增一个收货地址
    public String add(HttpServletRequest req, HttpServletResponse resp){
        String  sheng=req.getParameter("province");
        String  city=req.getParameter("city");
        String  area=req.getParameter("area");
        String detail=req.getParameter("detail");
        String uname=req.getParameter("uname");
        String utel=req.getParameter("utel");
        String  defaults=req.getParameter("setdefault");
        HttpSession  session=req.getSession();
        Object obj=session.getAttribute(SYS.USER);

        if (obj!=null&& obj instanceof User){
            User user=(User)obj;
            List<Area> as=areaService.getOneById(Integer.valueOf(sheng));
            sheng=as.get(0).getName();
            as=areaService.getOneById(Integer.valueOf(city));
            city=as.get(0).getName();

            String content=sheng+"省"+city+"市"+area+detail;

            Address addr=new Address();
            addr.setUid(user.getId());
            addr.setContent(content);
            addr.setUname(uname);
            addr.setUtel(utel);
            addr.setDefaults(0);
            if (defaults!=null&&defaults.equals("yes")){
                addr.setDefaults(1);
                int res=addressServic.clearDefault(user.getId());
                //继续完善错误信息
            }
            addressServic.addOne(addr);
//            String res= JSON.toJSONString(addr);
            return new String();

        }else {
            req.setAttribute("error","请登录先");
            return "r:logIn.jsp";
        }
    }

    //修改默认的收获地址
    public String setDefault(HttpServletRequest req, HttpServletResponse resp){

        HttpSession  session=req.getSession();
        Integer aid=Integer.valueOf(req.getParameter("aid"));
        Object obj=session.getAttribute(SYS.USER);
        if (obj!=null&& obj instanceof User) {
            User user = (User) obj;
            int uid=user.getId();
            int res1=addressServic.clearDefault(uid);
            if(res1!=0){
                int res2=addressServic.setDefault(uid,aid);
                if(res2==1){
                    return "{\"code\":1}";
                }
            }
        }
        return "{\"code\":0}";
    }
}
